package cn.liuyiyou.lean.es.service;

import cn.liuyiyou.lean.es.domain.BCoreHatch;
import cn.liuyiyou.lean.es.utils.JacksonUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpHost;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.builder.SearchSourceBuilder;

import java.io.IOException;
import java.util.Arrays;

/**
 * TODO
 *
 * @author liuyiyou
 * @version 1.0
 * @date 2021/7/6 8:59
 */
@Slf4j
public class EsTemplate {

    public void template(QueryBuilder queryBuilder, String indexName) throws IOException {

        RestHighLevelClient restHighLevelClient = new RestHighLevelClient(RestClient.builder(new HttpHost("10.240.5.19", 9200, "http")));
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();

        searchSourceBuilder.query(queryBuilder);

        SearchRequest searchRequest = new SearchRequest();
        searchRequest.indices(indexName);
        searchRequest.source(searchSourceBuilder);
        SearchResponse response = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);
        SearchHit[] hits = response.getHits().getHits();
        log.info("查询的大小是:{}", hits.length);
        Arrays.stream(hits).forEach(i -> {
            System.out.println(i.getSourceAsString());
            BCoreHatch hatch = JacksonUtils.parse(i.getSourceAsString(), BCoreHatch.class);
            log.error("id:{}\thandle:{}", i.getId(), hatch.getHandle());
        });
    }

    public void template(QueryBuilder queryBuilder) throws IOException {
        template(queryBuilder, "bcore_hatch");
    }
}
